
#import "social.h"
#import "wechat.h"
#import "facebook.h"
#import "gamecenter.h"

@implementation SocialResponse

-(id)init
{
    return [super init];
}
@end
@implementation SocialShareResponse

-(id)init
{
    return [super init];
}
@end
@implementation SocialAuthResponse

-(id)init
{
    return [super init];
}
@end
@implementation SocialUserInfoResponse
-(id)init
{
    return [super init];
}
@end
@implementation SocialMessageObject
-(id)init
{
    return [super init];
}
+ (SocialMessageObject *)messageObject{
    return [SocialMessageObject init];
}

@end
@implementation ShareObject

@end
@implementation ShareImageObject

@end
@implementation ShareMusicObject

@end
@implementation ShareVideoObject

@end
@implementation ShareWebpageObject

@end
@implementation ShareExtendObject

@end
@implementation ShareFileObject

@end
@implementation ShareMiniProgramObject

@end
@implementation SocialManager
{
    NSMutableDictionary *dictionary; // 平台存储
    NSDictionary *launchOptions;
}
static SocialManager* _instance = nil;


-(id)init
{
    self = [super init];
    self->dictionary = [[NSMutableDictionary alloc ]init];
    
    [self addPlatformProvider:[[GamecenterPlatformProvider alloc] init] withPlatformType: SocialPlatformType_GameCenter];
    [self addPlatformProvider:[[WechatPlatformProvider alloc] init] withPlatformType: SocialPlatformType_Wechat];
    [self addPlatformProvider:[[FacebookPlatformProvider alloc] init] withPlatformType: SocialPlatformType_Facebook];
    return self;
}
+(instancetype) defaultManager{
    static dispatch_once_t onceToken ;
    dispatch_once(&onceToken, ^{
        _instance = [[self alloc] init];
    }) ;
    
    return _instance ;
}

-(void)launch:(nullable NSDictionary *)launchOptions{
    self->launchOptions = launchOptions;
    NSEnumerator *enumeratorObject = [dictionary objectEnumerator];
    for (id object in enumeratorObject) {
        id<SocialPlatformProvider> platform = (id<SocialPlatformProvider>)object;
        [platform launch:launchOptions];
    }
}
- (BOOL)setPlatform:(SocialPlatformType)platformType
             appKey:(NSString *)appKey
          appSecret:(NSString *)appSecret
        redirectURL:(NSString *)redirectURL{
    id platform = [self->dictionary objectForKey:[NSNumber numberWithInt:platformType]];
    if (platform != NULL){
        platform = (id<SocialPlatformProvider>)platform;
        [platform setAppKey:appKey
              withAppSecret:appSecret
            withRedirectURL:redirectURL];
    }
    return true;
}

-(BOOL)handleOpenURL:(NSURL *)url{
    NSEnumerator *enumeratorObject = [dictionary objectEnumerator];
    for (id object in enumeratorObject) {
        id<SocialPlatformProvider> platform = (id<SocialPlatformProvider>)object;
        if ([platform handleOpenURL:url]){
            return true;
        }
    }
    return false;
}

-(BOOL)handleOpenURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{
    NSEnumerator *enumeratorObject = [dictionary objectEnumerator];
    for (id object in enumeratorObject) {
        id<SocialPlatformProvider> platform = (id<SocialPlatformProvider>)object;
        if ([platform handleOpenURL:url sourceApplication:sourceApplication annotation:annotation]){
            return true;
        }
    }
    return false;
}

-(BOOL)handleOpenURL:(NSURL *)url options:(NSDictionary*)options{
    NSEnumerator *enumeratorObject = [dictionary objectEnumerator];
    for (id object in enumeratorObject) {
        id<SocialPlatformProvider> platform = (id<SocialPlatformProvider>)object;
        if ([platform handleOpenURL:url options:options]){
            return true;
        }
    }
    return false;
}
-(BOOL)addPlatformProvider:(id<SocialPlatformProvider>)platformProvider
          withPlatformType:(SocialPlatformType)platformType{
    id platform = [self->dictionary objectForKey:[NSNumber numberWithInt:platformType]];
    if (platform != NULL){
        return false;
    }
    [dictionary setObject:platformProvider forKey:[NSNumber numberWithInt:platformType]];
    if (self->launchOptions != nil){
        [platformProvider launch:self->launchOptions];
    }
    return true;
}

-(id<SocialPlatformProvider>)platformProviderWithPlatformType:(SocialPlatformType)platformType{
    return (id<SocialPlatformProvider>)[self->dictionary objectForKey:[NSNumber numberWithInt:platformType]];
}

-(BOOL) isInstall:(SocialPlatformType)platformType{
    id platform = [self->dictionary objectForKey:[NSNumber numberWithInt:platformType]];
    if (platform != NULL){
        platform = (id<SocialPlatformProvider>)platform;
        return [platform isInstall];
    }
    return false;
}

-(BOOL) isSupport:(SocialPlatformType)platformType{
    id platform = [self->dictionary objectForKey:[NSNumber numberWithInt:platformType]];
    if (platform != NULL){
        platform = (id<SocialPlatformProvider>)platform;
        return [platform isSupport];
    }
    return false;
}

-(BOOL) isLeaderboard:(SocialPlatformType)platformType{
    id platform = [self->dictionary objectForKey:[NSNumber numberWithInt:platformType]];
    if (platform != NULL){
        platform = (id<SocialPlatformProvider>)platform;
        return [platform isLeaderboard];
    }
    return false;
}

-(BOOL) isAchievement:(SocialPlatformType)platformType{
    id platform = [self->dictionary objectForKey:[NSNumber numberWithInt:platformType]];
    if (platform != NULL){
        platform = (id<SocialPlatformProvider>)platform;
        return [platform isAchievement];
    }
    return false;
}

- (void)authWithPlatform:(SocialPlatformType)platformType
              completion:(SocialRequestCompletionHandler)completion{
    id platform = [self->dictionary objectForKey:[NSNumber numberWithInt:platformType]];
    if (platform != NULL){
        platform = (id<SocialPlatformProvider>)platform;
        [platform AuthorizeWithUserInfo:nil withCompletionHandler:completion];
    }
    return;
}

- (void)authStatusWithPlatform:(SocialPlatformType)platformType
                    completion:(SocialRequestCompletionHandler)completion{
    id platform = [self->dictionary objectForKey:[NSNumber numberWithInt:platformType]];
    if (platform != NULL){
        platform = (id<SocialPlatformProvider>)platform;
        [platform AuthorizedWithUserInfo:nil withCompletionHandler:completion];
    }
    return;
}

- (void)shareToPlatform:(SocialPlatformType)platformType
          messageObject:(SocialMessageObject *)messageObject
             completion:(SocialRequestCompletionHandler)completion{
    id platform = [self->dictionary objectForKey:[NSNumber numberWithInt:platformType]];
    if (platform != NULL){
        platform = (id<SocialPlatformProvider>)platform;
        [platform ShareWithObject:messageObject withCompletionHandler:completion];
    }
    return;
}

- (void)leaderboardToPlatform:(SocialPlatformType)platformType
          Key:(NSString *)key
          Value:(int) value
             completion:(SocialRequestCompletionHandler)completion{
    id platform = [self->dictionary objectForKey:[NSNumber numberWithInt:platformType]];
    if (platform != NULL){
        platform = (id<SocialPlatformProvider>)platform;
        [platform LeaderboardWith:key withValue:value withCompletionHandler:completion];
    }
    return;
}

- (void)achievementToPlatform:(SocialPlatformType)platformType
          Key:(NSString *)key
          Value:(int) value
             completion:(SocialRequestCompletionHandler)completion{
    id platform = [self->dictionary objectForKey:[NSNumber numberWithInt:platformType]];
    if (platform != NULL){
        platform = (id<SocialPlatformProvider>)platform;
        [platform AchievementWith:key withValue:value withCompletionHandler:completion];
    }
    return;
}

@end

NSString* getNSStringFromCStr(const char* cstr){
    if (cstr) {
        return [NSString stringWithUTF8String:cstr];
    }
    return nil;
}
int const platformlength = 4;
SocialPlatformType const platforms[platformlength] = {
    SocialPlatformType_GameCenter
    , SocialPlatformType_Wechat
    , SocialPlatformType_Facebook
};
SocialPlatformType getPlatform(int platform){
    for (int i = 0 ; i<platformlength; i++) {
        if (platform == platforms[i]) {
            return platforms[i];
        }
    }
    // todo
    return platforms[0];
}
UIViewController* getCurrentViewController(){
    
    UIViewController* ctrol = nil;
    //     UnityAppController *uni=[[UnityAppController alloc]init];
    //    ctrol = uni.window.rootViewController;
    if ( [[UIDevice currentDevice].systemVersion floatValue] < 6.0)
    {
        // warning: addSubView doesn't work on iOS6
        NSArray* array=[[UIApplication sharedApplication]windows];
        UIWindow* win=[array objectAtIndex:0];
        
        UIView* ui=[[win subviews] objectAtIndex:0];
        ctrol=(UIViewController*)[ui nextResponder];
    }
    else
    {
        
        // use this method on ios6
        ctrol=[UIApplication sharedApplication].keyWindow.rootViewController;
    }
    return ctrol;
}
id getImageFromFilePath(const char* imagePath){
    id returnImage = nil;
    
    if (imagePath) {
        NSString *imageString = [NSString stringWithUTF8String:imagePath];
        
        if ([imageString hasPrefix:@"http"]) {
            returnImage = imageString;
        }else{
            returnImage = [UIImage imageNamed:imageString];
        }
        
    }
    return returnImage;
    //    if (imagePath) {
    //        NSString *imageString = getNSStringFromCStr(imagePath);
    //        //传入整个路径
    //        if ([imageString rangeOfString:@"/"].length > 0){
    //            if ([imageString.lowercaseString hasSuffix:@".gif"]) {
    //                NSString *path = [[NSBundle mainBundle] pathForResource:[[imageString componentsSeparatedByString:@"."] objectAtIndex:0]
    //                                                                 ofType:@"gif"];
    //
    //                returnImage = [NSData dataWithContentsOfFile:path];
    //            } else{
    //                returnImage = [UIImage imageNamed:getNSStringFromCStr(imagePath)];
    //            }
    //        }
    //        else {      //只传文件名
    //            if ([imageString.lowercaseString hasSuffix:@".gif"]) {
    //                NSString *path = [[NSBundle mainBundle] pathForResource:[[imageString componentsSeparatedByString:@"."] objectAtIndex:0]
    //                                                                 ofType:@"gif"];
    //
    //                returnImage = [NSData dataWithContentsOfFile:path];
    //            } else{
    //                returnImage = [UIImage imageNamed:getNSStringFromCStr(imagePath)];
    //            }
    //        }
    ////        NSLog(@"return Image is %@",returnImage);
    //      //  [UMSocialData defaultData].urlResource.resourceType = UMSocialUrlResourceTypeDefault;
    //    }
    //    return returnImage;
}
extern "C" {
    
    typedef void (*RegisterHandler)(int platform, bool isInstall, bool isShared);
    typedef void (*AuthHandler)(int platform, int stCode, const char * key, const char * value);
    typedef void (*LogoutDelegate)(int platform);
    typedef void (*RealDelegate)(int platform, int stCode, const char * errorMsg);
    typedef void (*ShareDelegate)(int platform, int stCode, const char * errorMsg);
    typedef void (*LeaderboardDelegate)(int platform, int stCode, const char * errorMsg);
    typedef void (*AchievementDelegate)(int platform, int stCode, const char * errorMsg);

    // 注册社交平台信息
    void registerPlatform(int platform, const char* appId, RegisterHandler callback){
        NSString* nsappId = [NSString stringWithUTF8String:appId];
        
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC));
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [[SocialManager defaultManager] setPlatform:getPlatform(platform) appKey: nsappId appSecret: nil redirectURL: nil];
            bool result1 = [[SocialManager defaultManager] isInstall:getPlatform(platform)];
            bool result2 = [[SocialManager defaultManager] isSupport:getPlatform(platform)];
            callback(platform, result1, result2);
        });
    }
    
    //授权某社交平台
    void authorize(int platform, AuthHandler callback){
        [[SocialManager defaultManager]  authWithPlatform:getPlatform(platform) completion:^(id result, NSError *error) {
            NSLog(@" auth call back");
            NSString *message = nil;
            int code = 200;
            NSString *key =@"";
            NSString *value = @"";
            if (error) {
                NSLog(@"Auth fail with error %@", error);
                message = @"Auth fail";
                code = error.code;
                key = [key stringByAppendingString:@"mesaage"];
                value=[value stringByAppendingString:message];
            }else{
                if ([result isKindOfClass:[SocialUserInfoResponse class]]) {
                    SocialUserInfoResponse *resp = result;
                    // 授权信息
                    if (resp.openId) {
                        key = [key stringByAppendingString:@"openId"];
                        value=[value stringByAppendingString:resp.openId];
                    }
                    
                    if (resp.accessToken) {
                        key = [key stringByAppendingString:@",accessToken"];
                        value=[value stringByAppendingString:@","];
                        value=[value stringByAppendingString:resp.accessToken];
                    }
                    
                    if (resp.refreshToken) {
                        key = [key stringByAppendingString:@",refreshToken"];
                        value=[value stringByAppendingString:@","];
                        value=[value stringByAppendingString:resp.refreshToken];
                    }
                    if (resp.nickName) {
                        key = [key stringByAppendingString:@",nickName"];
                        value=[value stringByAppendingString:@","];
                        value=[value stringByAppendingString:resp.nickName];
                    }
                    if (resp.gender) {
                        key = [key stringByAppendingString:@",gender"];
                        value=[value stringByAppendingString:@","];
                        value=[value stringByAppendingString:resp.gender];
                    }
                    if (resp.avatar) {
                        key = [key stringByAppendingString:@",avatar"];
                        value=[value stringByAppendingString:@","];
                        value=[value stringByAppendingString:resp.avatar];
                    }
                    
                } else if ([result isKindOfClass:[SocialAuthResponse class]]) {
                    SocialAuthResponse *resp = result;
                    // 授权信息
                    if (resp.code) {
                        key = [key stringByAppendingString:@"code"];
                        value=[value stringByAppendingString:resp.code];
                    }
                    
                    if (resp.state) {
                        key = [key stringByAppendingString:@",state"];
                        value=[value stringByAppendingString:@","];
                        value=[value stringByAppendingString:resp.state];
                    }
                } else {
                    NSLog(@"Auth fail with unknow error");
                    key = [key stringByAppendingString:@"mesaage"];
                    value=[value stringByAppendingString:@"Auth fail with unknow error"];
                }
            }
            NSLog(@"key=%s",[key UTF8String]);
            NSLog(@"value=%s",[value UTF8String]);
            callback(platform, code, [key UTF8String], [value UTF8String]);
        }];
    }
    //授权某社交平台
    void isAuthorized(int platform, AuthHandler callback){
        [[SocialManager defaultManager]  authStatusWithPlatform:getPlatform(platform) completion:^(id result, NSError *error) {
            NSLog(@" auth call back");
            NSString *message = nil;
            int code = 200;
            NSString *key =@"";
            NSString *value = @"";
            if (error) {
                NSLog(@"Auth fail with error %@", error);
                message = @"Auth fail";
                code = error.code;
                key = [key stringByAppendingString:@"mesaage"];
                value=[value stringByAppendingString:message];
            }else{
                if ([result isKindOfClass:[SocialUserInfoResponse class]]) {
                    SocialUserInfoResponse *resp = result;
                    // 授权信息
                    if (resp.openId) {
                        key = [key stringByAppendingString:@"openId"];
                        value=[value stringByAppendingString:resp.openId];
                    }
                    
                    if (resp.accessToken) {
                        key = [key stringByAppendingString:@",accessToken"];
                        value=[value stringByAppendingString:@","];
                        value=[value stringByAppendingString:resp.accessToken];
                    }
                    
                    if (resp.refreshToken) {
                        key = [key stringByAppendingString:@",refreshToken"];
                        value=[value stringByAppendingString:@","];
                        value=[value stringByAppendingString:resp.refreshToken];
                    }
                    if (resp.nickName) {
                        key = [key stringByAppendingString:@",nickName"];
                        value=[value stringByAppendingString:@","];
                        value=[value stringByAppendingString:resp.nickName];
                    }
                    if (resp.gender) {
                        key = [key stringByAppendingString:@",gender"];
                        value=[value stringByAppendingString:@","];
                        value=[value stringByAppendingString:resp.gender];
                    }
                    if (resp.avatar) {
                        key = [key stringByAppendingString:@",avatar"];
                        value=[value stringByAppendingString:@","];
                        value=[value stringByAppendingString:resp.avatar];
                    }
                    
                } else if ([result isKindOfClass:[SocialAuthResponse class]]) {
                    SocialAuthResponse *resp = result;
                    // 授权信息
                    if (resp.code) {
                        key = [key stringByAppendingString:@"code"];
                        value=[value stringByAppendingString:resp.code];
                    }
                    
                    if (resp.state) {
                        key = [key stringByAppendingString:@",state"];
                        value=[value stringByAppendingString:@","];
                        value=[value stringByAppendingString:resp.state];
                    }
                } else {
                    NSLog(@"Auth fail with unknow error");
                    key = [key stringByAppendingString:@"mesaage"];
                    value=[value stringByAppendingString:@"Auth fail with unknow error"];
                }
            }
            NSLog(@"key=%s",[key UTF8String]);
            NSLog(@"value=%s",[value UTF8String]);
            callback(platform, code, [key UTF8String], [value UTF8String]);
        }];
    }

    void logoutPlatform(int platform, LogoutDelegate callback){
        
    }
    void real(int platform, RealDelegate callback){
        
    }
    
    //直接分享到各个社交平台
    void directShare(int platform, const char* title, const char* imagePath, const char* description, const char* targetUrl, const char* videoUrl, ShareDelegate callback){
        id image = nil;
        NSString* nstargeturl = [NSString stringWithUTF8String:targetUrl];
        NSString* nsvideoturl = [NSString stringWithUTF8String:videoUrl];
        NSString* nstitle = [NSString stringWithUTF8String:title];
        NSString* nsdescription = [NSString stringWithUTF8String:description];
        //    NSLog(@"targetUrl:%@", nstargeturl);
        image = getImageFromFilePath(imagePath);
        SocialMessageObject *messageObject = [SocialMessageObject messageObject];
        if (nstargeturl==nil||nstargeturl.length==0) {
            if (image==nil) {
                
                messageObject.title =  nstitle;
            }else{
                ShareImageObject *shareObject = [[ShareImageObject alloc] init];
                shareObject.shareImage = image;
                shareObject.title = nstitle;
                shareObject.description = nsdescription;
                messageObject.shareObject = shareObject;
            }
        }else if (nsvideoturl!=nil&&nsvideoturl.length>0){
            //创建视频内容对象
            ShareVideoObject *shareObject = [[ShareVideoObject alloc] init];
            shareObject.title = nstitle;
            shareObject.description = nsdescription;
            //设置视频网页播放地址
            shareObject.videoUrl = nstargeturl;
            shareObject.videoStreamUrl = nsvideoturl;
            
            //分享消息对象设置分享内容对象
            messageObject.shareObject = shareObject;
            messageObject.title = nstitle;
        }else{
            messageObject.title = nstitle;
            ShareWebpageObject *shareObject = [[ShareWebpageObject alloc] init];
            shareObject.title = nstitle;
            shareObject.description = nsdescription;
            //设置网页地址
            shareObject.webpageUrl =nstargeturl;
            //分享消息对象设置分享内容对象
            messageObject.shareObject = shareObject;
        }
        
        [[SocialManager defaultManager] shareToPlatform:getPlatform(platform) messageObject:messageObject completion:^(id data, NSError *error) {
            int code;
            NSLog(@"dddddd");
            NSString* message;
            if (error) {
                code = error.code;
                NSLog(@"************Share fail with error %@*********",error);
                message =error.description;
            }else{
                code = 200;
                if ([data isKindOfClass:[SocialShareResponse class]]) {
                    SocialShareResponse *resp = data;
                    //分享结果消息
                    NSLog(@"response message is %@",resp.message);
                    //第三方原始返回的数据
                    NSLog(@"response originalResponse data is %@",resp.originalResponse);
                    code = 200;
                    message =@"success";
                }else{
                    NSLog(@"response data is %@",data);
                    message =@"unkonw fail";
                }
            }
            callback(platform, code, [message UTF8String]);
            
        }];
        
    }

    void updateData(int platform, const char* key, const char* value){
        
    }

    //直接提交到排行榜
    void submitLeaderboard(int platform, const char* key, int value, LeaderboardDelegate callback){
        NSString* nsKey = [NSString stringWithUTF8String:key];
        
        [[SocialManager defaultManager] leaderboardToPlatform:getPlatform(platform) Key:nsKey Value:value completion:^(id data, NSError *error) {
            int code;
            NSString* message;
            if (error) {
                code = error.code;
                NSLog(@"************Leaderboard fail with error %@*********",error);
                message =error.description;
            }else{
                code = 200;
                message =@"success";
            }
            callback(platform, code, [message UTF8String]);
        }];
    }

    //直接提交到成就
    void addAchievement(int platform, const char* key, int value, AchievementDelegate callback){
        NSString* nsKey = [NSString stringWithUTF8String:key];
        
        [[SocialManager defaultManager] achievementToPlatform:getPlatform(platform) Key:nsKey Value:value completion:^(id data, NSError *error) {
            int code;
            NSString* message;
            if (error) {
                code = error.code;
                NSLog(@"************Achievement fail with error %@*********",error);
                message =error.description;
            }else{
                code = 200;
                message =@"success";
            }
            callback(platform, code, [message UTF8String]);
        }];
    }
    
}
